package cn.relx.org.service.impl;

import cn.relx.basic.service.impl.BaseServiceImpl;
import cn.relx.org.domain.Employee;
import cn.relx.org.mapper.EmployeeMapper;
import cn.relx.org.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> empDepartmentId() {
        List<Employee> allDepts = employeeMapper.findAll();
        // stream
        Map<Long, Employee> parentMap = allDepts.stream().collect(Collectors.toMap(Employee::getId, e -> e));
        // 同理
//        Map<Long, Department> parentMap = new HashMap<>();
//        for (Department dept : allDepts) {
//            parentMap.put(dept.getId(),dept);
//        }
        List<Employee> result = new ArrayList<>();
        // 遍历
        for (Employee dept : allDepts) {
            if (null == dept.getDepartmentId()) {
                // 它就是最大的那个die
                result.add(dept);
            } else {
                // 当前的这个dept 是个儿子
                // 找爹 自己是个儿子 有爹的id
                Employee parent = parentMap.get(dept.getDepartmentId());
                List<Employee> children = parent.getChildren();
                children.add(dept);
            }
        }
        return result;
    }


}
